<?php
chdir("../");
require "../config/config.php";
require "../config/attributes.php";
require GALAXYTOOL_ROOT."/secret/includes/authorization.inc.php";
session_start();
$NO_PAGE_FORWARD = true;
require GALAXYTOOL_ROOT."/secret/includes/logincheck.inc.php";
if (isset($error_page_code) && $error_page_code == "timeout") exit("");
if (!isset($_GET['type'])) exit("");


require GALAXYTOOL_ROOT."/secret/includes/messages.inc.php";
try {
	$msg_obj = new Messages($global_mysql_con,$messagetable,$noticetable,$playertable);
} catch (Exception $e) {
	exit("Exception occurred: ".$e);
}

$type = $_GET['type'];

switch ($type) {
	case "overview":
		// return content as json format
		header("Content-type: application/json");
		header("Pragma: no-cache");
		header("Expires: 0");

		if (isset($_GET['playerid']) && is_numeric($_GET['playerid'])) {
			$playerid = intval($_GET['playerid']);
			echo $msg_obj->get_message_overview($playerid);
		} else {
			echo $msg_obj->get_message_overview();
		}

		break;

	case "content":
		header("content-type: text/html; charset=utf-8");
		header("Pragma: no-cache");
		header("Expires: 0");

		if (!isset($_GET['id']) || !is_numeric($_GET['id'])) exit();
		$id = intval($_GET['id']);
		$result = $msg_obj->get_message_content($id);

		$messages = $msg_obj->get_error_object();
		$message_json = ($messages != null) ? $messages->get_JSON_result() : "null";
		$result = '{ result: '.json_encode($result).' , messages: '.$message_json.' }';
		exit($result);
		break;

	case "publish":
		header("content-type: text/html; charset=utf-8");
		header("Pragma: no-cache");
		header("Expires: 0");

		if (!isset($_GET['id']) || !is_numeric($_GET['id'])) exit();
		$id = intval($_GET['id']);

		if (!isset($_SESSION['lang'])) $_SESSION['lang'] = $default_language;
		Galaxytool::load_language_file($_SESSION['lang']);
		$result = $msg_obj->publish_message($id);

		$messages = $msg_obj->get_error_object();
		$message_json = ($messages != null) ? $messages->get_JSON_result() : "null";
		$result = '{ result: '.json_encode($result).' , messages: '.$message_json.' }';
		exit($result);

	case "delete":
		header("content-type: text/html; charset=utf-8");
		header("Pragma: no-cache");
		header("Expires: 0");
		// do not check for delete permission! Only own ingame messages can be deleted

		if (!isset($_GET['id']) || !is_numeric($_GET['id'])) exit();
		$id = intval($_GET['id']);
		$result = $msg_obj->delete_message($id);

		$messages = $msg_obj->get_error_object();
		$message_json = ($messages != null) ? $messages->get_JSON_result() : "null";
		$result = '{ result: '.json_encode($result).' , messages: '.$message_json.' }';
		exit($result);

}